<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <div v-if="switchFlag">
        <Row class="query-form">
          <Col span="8">
            <FormItem label="企业名称：">
              <Input class="query-form-el" type="text" v-model="form1.companyName"></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="年份：">
              <DatePicker type="year" v-model="form1.vehicleYear" format="yyyy"
                          placeholder="选择年份"  style="width: 100%"></DatePicker>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="季度：">
              <Select style="width:100%"  v-model="form1.quarter" >
                <Option v-for="item in quarterLists" :value="item.codingCodeId">{{item.codingName}}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row class="query-form2">
          <Col span="24">
            <div style="float: right;">
              <div style="float: right;">
                <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <div v-else>
        <Row class="query-form2">
          <Col span="8">
            <FormItem label="企业名称：">
              <Input class="query-form-el" type="text" v-model="form1.companyName"></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="年份：">
              <DatePicker type="year" v-model="form1.vehicleYear"  format="yyyy"
                          placeholder="选择年份" style="width: 100%"></DatePicker>
            </FormItem>
          </Col>
          <Col span="8">
            <div style="float: right;">
              <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
              <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
            </div>
          </Col>
        </Row>
      </div>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :loading="loading" size="small" :height="tableHeight" class="no-add-table"
           no-data-text="没有查询到相关数据!"  :span-method="handleSpan"
           highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              style="float: right" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :title="title" :transfer=false v-model="model1" :width=800>
      <Row>
        <Col span="24">
          <Form ref="dataToView" :label-position="mode === 'view'?'right':'top'" :model="dataToView" :rules="ruleCustom">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='企业名称：' prop='companyId'>
                  <div v-if="mode === 'view'">{{dataToView.companyName}}</div>
                  <cascader-dom v-else class='query-form-el' ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName" :orgTree="true"
                                :currentOrgId="dataToView.companyId" :rootOrgId="dataToView.belongOrgId"
                                :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}" ></cascader-dom>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="年份：" prop="vehicleYear">
                  <div v-if="mode === 'view'">{{ dataToView.vehicleYear }}</div>
                  <DatePicker v-else style="width:100%" type="year"
                              format="yyyy"
                              placeholder="选择年份" v-model="dataToView.vehicleYear"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="季度：" prop="quarter">
                  <div v-if="mode === 'view'">{{ dataToView.quarterDesc }}</div>
                  <Select v-else style="width:100%"  v-model="dataToView.quarter" >
                    <Option v-for="item in quarterLists" :value="item.codingCodeId">{{item.codingName}}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Divider orientation="left">国五</Divider>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="车次：" prop="vehicleNum">
                  <div v-if="mode === 'view'">{{ dataToView.vehicleNum0 }}</div>
                  <InputNumber v-else style="width:100%" :step="1" type="text" v-model="dataToView.vehicleNum0" />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="运输量：" prop="volume">
                  <div v-if="mode === 'view'">{{ dataToView.volume0 }}</div>
                  <InputNumber v-else style="width:100%" :step="0.1" type="text" v-model="dataToView.volume0" />
                </FormItem>
              </Col>
            </Row>
            <Divider orientation="left">国六</Divider>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="车次：" prop="vehicleNum">
                  <div v-if="mode === 'view'">{{ dataToView.vehicleNum1 }}</div>
                  <InputNumber v-else style="width:100%" :step="1" type="text" v-model="dataToView.vehicleNum1" />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="运输量：" prop="volume">
                  <div v-if="mode === 'view'">{{ dataToView.volume1 }}</div>
                  <InputNumber v-else style="width:100%" :step="0.1" type="text" v-model="dataToView.volume1" />
                </FormItem>
              </Col>
            </Row>
            <Divider orientation="left">新能源</Divider>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="车次：" prop="vehicleNum">
                  <div v-if="mode === 'view'">{{ dataToView.vehicleNum2 }}</div>
                  <InputNumber v-else style="width:100%" :step="1" type="text" v-model="dataToView.vehicleNum2" />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="运输量：" prop="volume">
                  <div v-if="mode === 'view'">{{ dataToView.volume2 }}</div>
                  <InputNumber v-else style="width:100%" :step="0.1" type="text" v-model="dataToView.volume2" />
                </FormItem>
              </Col>
            </Row>
            <Divider orientation="left">国五以下</Divider>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="车次：" prop="vehicleNum3">
                  <div v-if="mode === 'view'">{{ dataToView.vehicleNum3 }}</div>
                  <InputNumber v-else style="width:100%" :step="1" type="text" v-model="dataToView.vehicleNum3" />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="运输量：" prop="volume3">
                  <div v-if="mode === 'view'">{{ dataToView.volume3 }}</div>
                  <InputNumber v-else style="width:100%" :step="0.1" type="text" v-model="dataToView.volume3" />
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" @click="submit('dataToView')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button v-if="mode != 'view'" @click="model1 = false" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import pageCommonFunction from '@/components/pageCommonFunction.js'
var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  components: {cascaderDom},
  name: "freightVehicles",
  data() {
    return {
      ...this.createCommonDataField(),
      date: ['', ''],
      loading: false, tableHeight: '',
      form1: {
        companyName: '',
      },
      switchFlag: false,
      buttonLoading:false,
      title:'',
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      companyId: sessionStorage('userId').getObject('userId').companyId,
      dataTable: [],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          minWidth: 300,
          title: '单位名称',
          align: 'center',
          fixed: 'left',
          key: 'companyName',
        },
        {
          minWidth: 100,
          title: '年份',
          align: 'center',
          key: 'vehicleYear',
        },
        {
          minWidth: 100,
          title: '季度',
          align: 'center',
          key: 'quarterDesc',
        },
        {
          minWidth: 400,
          title: "国五",
          align: 'center',
          children: [
            {
              minWidth: 100,
              title: "车次",
              align: 'center',
              key: 'vehicleNum0'
            },
            {
              minWidth: 100,
              title: "车次占比（%）",
              align: 'center',
              key: 'vehicleNumPer0'
            },
            {
              minWidth: 100,
              title: "运输量（吨）",
              align: 'center',
              key: 'volume0'
            },
            {
              minWidth: 100,
              title: "运输量占比（%）",
              align: 'center',
              key: 'volumePer0'
            }
          ]
        },
        {
          minWidth: 400,
          title: "国六",
          align: 'center',
          children: [
            {
              minWidth: 100,
              title: "车次",
              align: 'center',
              key: 'vehicleNum1'
            },
            {
              minWidth: 100,
              title: "车次占比（%）",
              align: 'center',
              key: 'vehicleNumPer1'
            },
            {
              minWidth: 100,
              title: "运输量（吨）",
              align: 'center',
              key: 'volume1'
            },
            {
              minWidth: 100,
              title: "运输量占比（%）",
              align: 'center',
              key: 'volumePer1'
            }
          ]
        },
        {
          minWidth: 400,
          title: "新能源",
          align: 'center',
          children: [
            {
              minWidth: 100,
              title: "车次",
              align: 'center',
              key: 'vehicleNum2'
            },
            {
              minWidth: 100,
              title: "车次占比（%）",
              align: 'center',
              key: 'vehicleNumPer2'
            },
            {
              minWidth: 100,
              title: "运输量（吨）",
              align: 'center',
              key: 'volume2'
            },
            {
              minWidth: 100,
              title: "运输量占比（%）",
              align: 'center',
              key: 'volumePer2'
            }
          ]
        },
        {
          minWidth: 400,
          title: "国五以下",
          align: 'center',
          children: [
            {
              minWidth: 100,
              title: "车次",
              align: 'center',
              key: 'vehicleNum3'
            },
            {
              minWidth: 100,
              title: "车次占比（%）",
              align: 'center',
              key: 'vehicleNumPer3'
            },
            {
              minWidth: 100,
              title: "运输量（吨）",
              align: 'center',
              key: 'volume3'
            },
            {
              minWidth: 100,
              title: "运输量占比（%）",
              align: 'center',
              key: 'volumePer3'
            }
          ]
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            let flag =(this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId
                || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined||
                (this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined &&
                    params.row.orgCode && params.row.orgCode.indexOf(this.currentUser.companyCode)!=-1))
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {style: {
                    fontSize: '14px',
                    color:flag?'':'#c5c8ce',
                    pointerEvents:flag?'':'none'
                  },
                  click: () => {
                    this.showData(params, 1);
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:flag?'red':'#c5c8ce',
                  pointerEvents:flag?'':'none'
                },
                on: {
                  click: () => {
                    this.showData(params, 2);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:flag?'red':'#c5c8ce',
                  pointerEvents:flag?'':'none'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deleteData(params);
                      },
                      cancelText: '取消'
                    });
                  }
                }
              }, '删除'),
            ]);
          }
        }
      ],
      model1: false,
      model2: false,
      buttonDisabled: false,
      vehicleTypes:[],
      quarterLists:[],
      InputData: {},
      ruleCustom: {
        quarter: [ { required: true, message: '请选择季度', trigger: 'change',}]
      },
    }
  },
  async mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.form1.vehicleYear = new Date();
    this.loading = true;
    await this.selectCodingSort();
    this.query()
  },
  methods: {
    ...pageCommonFunction,
    vehiclesTypeChange(item){

    },
    handleSpan({ row, column, rowIndex, columnIndex }) {
      if(columnIndex == 1 || columnIndex == 2){
        if(row.span != 0)
          return [row.span, 1];
        else
          return [0,0];
      }
    },
    switchQuery(flag){
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 30;
      } else {
        this.tableHeight = this.tableHeight - 30;
      }
    },
    async selectCodingSort() {
      await this.$http.get(Api.queryCodeDetailBySortId + '/FV-00002', {params: {}}).then((res) => {
        this.quarterLists = res.data.data;
      })
    },
    addInfo(){
      this.mode = "add";
      this.dataToView = {
        vehicleNum0:null,
        vehicleNum1:null,
        vehicleNum2:null,
        vehicleNum3:null,
        volume0:null,
        volume1:null,
        volume2:null,
        volume3:null,
      };
      this.dataToView.companyId = sessionStorage('userId').getObject('userId').companyId;
      this.dataToView.companyName = sessionStorage('userId').getObject('userId').companyName;
      let date = new Date();
      this.dataToView.vehicleYear = date.getFullYear() + "";
      setTimeout(() => {
        this.$refs.orgCascader.setCurrentOrg();
      }, 100)
      this.title = "货运车辆新增";
      this.model1 = true;
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let date = new Date(this.dataToView.vehicleYear );
          this.dataToView.vehicleYear = date.getFullYear() + "";
          this.$http.post(Api.saveFreightVehicles, this.dataToView).then((res) => {
            if(res.data.status == 200){
              this.$Message.success("保存成功")
              this.model1 = false;
              this.query();
              this.buttonLoading = false;
            }
            else  if(res.data.msg == "数据已存在")
              this.$Message.error("当前季度数据已存在")
          }).catch(e => {
            this.model1 = false;
            this.query();
            this.$Message.error("数据获取失败")
          })
        }
      })
    },
    showData(data, flag) {
      this.buttonLoading = false;
      this.dataToView = JSON.parse(JSON.stringify(data.row));
      if (flag == 1) {
        //查看页面
        this.mode = "view";
        this.model1 = true;
        this.title = "货运车辆详情";
      } else {
        this.mode = "modify";
        this.title = "货运车辆修改";
        this.dataToView.vehicleYear = this.dataToView.vehicleYear + "";
        if(this.dataToView.vehicleNum1 == undefined)
          this.dataToView.vehicleNum1 = null;
        if(this.dataToView.vehicleNum2 == undefined)
          this.dataToView.vehicleNum2 = null;
        if(this.dataToView.vehicleNum0 == undefined)
          this.dataToView.vehicleNum0 = null;
        if(this.dataToView.vehicleNum3 == undefined)
          this.dataToView.vehicleNum3 = null;
        if(this.dataToView.volume1 == undefined)
          this.dataToView.volume1 = null;
        if(this.dataToView.volume0 == undefined)
          this.dataToView.volume0 = null;
        if(this.dataToView.volume2 == undefined)
          this.dataToView.volume2 = null;
        if(this.dataToView.volume3== undefined)
          this.dataToView.volume3 = null;
        setTimeout(() => {
          this.$refs.orgCascader.setCurrentOrg();
        }, 100)
        this.model1 = true;
      }
    },
    deleteData(params) {
      let url = Api.deleteFreightVehicles;
      this.$http.delete(url + '/' + params.row.id).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    query() {
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        companyId: sessionStorage('userId').getObject('userId').companyId,
        companyName : this.form1.companyName,
        quarter: this.form1.quarter
      };
      if(this.form1.vehicleYear != "" && this.form1.vehicleYear != undefined) {
        let date = new Date(this.form1.vehicleYear);
        data.vehicleYear = date.getFullYear() + "";
      }

      let url = Api.queryFreightVehicles
      this.$http.get(url, {params: data}).then((res) => {
        if(res.data.status == 200) {
          this.dataTable = res.data.data.data;
          this.pagedata.total = res.data.data.total;
        }else{
          this.dataTable = [];
          this.pagedata.total = 0;
          this.$Message.error("数据获取失败")
        }
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {
        companyName: '',
        vehicleYear : new Date(),
        quarter: ''
      }
      this.query();
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
  }
}
</script>

<style lang='css' scoped>
@import '../../../index.css';

</style>